package com.xzjt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzjt.entity.SysUser;
import com.xzjt.entity.SysUserRole;
import com.xzjt.mapper.SysUserMapper;
import com.xzjt.mapper.SysUserRoleMapper;
import com.xzjt.service.SysUserService;
import com.xzjt.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: SysUserServiceImpl
 * @Author: yuandong
 * @Date 2021/10/9 15:59
 */
@Service
public class SysUserServiceImpl implements SysUserService  {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;




    public List<SysUser> selectUserList(SysUser sysUser){
       return sysUserMapper.selectUserList(sysUser);

    }

    @Override
    public SysUser selectLoginUser(SysUser user) {
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, user.getUsername()).eq(SysUser::getPassword, user.getPassword()));
        return sysUser;
    }

    @Override
    public Page<SysUser> selectPage(Page<SysUser> page, QueryWrapper queryWrapper) {
        return sysUserMapper.selectPage(page, queryWrapper);
    }

    @Override
    public SysUser selectByUsername(String username){
        return sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
    }


    /**
     * 保存用户（并关联角色）
     * @param user
     * @return
     */
    @Override
    public int save(SysUser user) {
        sysUserMapper.insert(user);

        //新增用户与角色(暂定一个用户只能选取一个角色)
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setRoleId(user.getRoleId());
        sysUserRole.setUserId(user.getId());
        int flag = userRoleMapper.insert(sysUserRole);

        return flag;
    }


    @Override
    public int updateUserById(SysUser user) {
        //1.先删除用户和角色的关联
        this.userRoleMapper.deleteUserRoleByUserId(user.getId());

        //2.重新建立用户和角色的关系
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setRoleId(user.getRoleId());
        sysUserRole.setUserId(user.getId());

        userRoleMapper.insert(sysUserRole);
        return sysUserMapper.updateById(user);
    }

    @Override
    public int checkUserNameUnique(String userName) {
        return sysUserMapper.checkUserNameUnique(userName);
    }


}
